# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _, tools
import json


class Nc2OdsWizard(models.TransientModel):
    _name = "fp.nc2ods.wizard"
    _description = "Nc to Ods Wizard"

    nc_order_ids = fields.Many2many(
        'fp.nc.ods.sale.order',
        'fp_nc2ods_nc_rel',
        'wizard_id', 'nc_order_id',
        string="NC Order", readonly=True, copy=False,)

    @api.model
    def _values_get_by_nc(self, nc_orders):
        return {
            'nc_order_ids': [(6, 0, nc_orders.ids)],
        }

    def onchange(self, values, field_name, field_onchange):
        result = super().onchange(values, field_name, field_onchange)
        if field_name:
            return result

        active_ids = self._context.get('active_ids', [])
        ods_obj = self.env['fp.nc.ods.sale.order']
        nc_orders = ods_obj.browse(active_ids)

        default_vals = self._values_get_by_nc(nc_orders)
        result['value'].update(default_vals)
        return result

    @api.model_create_multi
    def create(self, vals_list):
        # self._context.get('active_model') == 'fp.ods.sale.order'
        active_ids = self._context.get('active_ids', [])
        ods_obj = self.env['fp.nc.ods.sale.order']
        nc_orders = ods_obj.browse(active_ids)

        for vals in vals_list:
            default_vals = self._values_get_by_nc(nc_orders)
            vals.update(default_vals)

        records = super().create(vals_list)

        return records

    def create_ods_order(self):

        ods_orders_res = None

        for order in self.nc_order_ids:
            ods_orders = order.load_to_model()
            if not ods_orders_res:
                ods_orders_res = ods_orders
            else:
                ods_orders_res = ods_orders_res | ods_orders

        return ods_orders_res.ids
